package com.bupt.service.system.impl;

import com.bupt.constants.InitConstants;
import com.bupt.dao.TbSystemUserMapper;
import com.bupt.exception.BaseException;
import com.bupt.model.TbSystemUser;
import com.bupt.model.TbSystemUserExample;
import com.bupt.service.system.SysUserService;
import com.bupt.utils.LocalVerify;
import com.bupt.utils.PassWordUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service("systemUserService")
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private TbSystemUserMapper tbSystemUserMapper;
    /**
     *
     * 用户注册的基本注册
     * @param userName  用户名
     * @param password  密码
     * @param rePassword 确认密码
     * @return
     * @throws BaseException
     */
    @Override
    public Object registerUser(String userName, String password, String rePassword) throws BaseException {
        LocalVerify.verifyStringIsNotNull(userName,password,rePassword);
        if(StringUtils.equals(password,rePassword)) {
            synchronized (SysUserServiceImpl.class) {
                TbSystemUserExample tbSystemUserExample = new TbSystemUserExample();
                tbSystemUserExample.createCriteria().andUserNameEqualTo(userName);
                List<TbSystemUser> tbSystemUsers = tbSystemUserMapper.selectByExample(tbSystemUserExample);
                if (null != tbSystemUsers && tbSystemUsers.size() > 0) {
                    throw new BaseException("用户名已存在");
                } else {
                    TbSystemUser tbSystemUser = new TbSystemUser();
                    String pk = UUID.randomUUID().toString();
                    tbSystemUser.setuId(pk);
                    tbSystemUser.setUserName(userName);
                    String passwordSalt = UUID.randomUUID().toString();
                    // 获得数据库的密码
                    String dbPassWord = PassWordUtils.getDbPassWord(password, passwordSalt);
                    tbSystemUser.setUserPassword(dbPassWord);
                    tbSystemUser.setPassowrdSalt(passwordSalt);
                    Date nowTime = new Date();
                    tbSystemUser.setGmtCreate(nowTime);
                    try {
                        tbSystemUserMapper.insertSelective(tbSystemUser);
                        return InitConstants.OK_MESSAGE;
                    } catch (Exception e) {
                        throw new BaseException(e.getMessage());
                    }
                }
            }
        }else {
            throw  new BaseException("两次输入密码不一致");
        }
    }
}
